from typing import Optional, List, Dict, Any
from apps.models.models import Training_Categories, User, Training_Programs
from apps.schemas.schemas import CategoryCreateRequest, CategoryUpdateRequest
from tortoise.transactions import in_transaction


async def get_all_categories():
    categories = await Training_Categories.all().values(
        'category_id', 'name', 'description', 'create_by_id', 'create_at', 'update_at', 'is_active'
    )
    return list(categories)


async def create_category(data: CategoryCreateRequest) -> Dict[str, Any]:
    # 检查类名是否存在
    existing_category = await Training_Categories.get_or_none(name=data.name)
    if existing_category:
        raise ValueError("Category name already exists")

    # 获取当前用户
    current_user = await User.get_or_none(user_id=data.create_by_id)
    if not current_user:
        raise ValueError("User not found")

    async with in_transaction() as connection:
        category = await Training_Categories.create(
            name=data.name,
            description=data.description,
            create_by=current_user,
            using_db=connection
        )

    return {
        "category_id": category.category_id,
        "name": category.name,
        "description": category.description,
        "create_by_id": category.create_by_id
    }


async def update_category(category_id: int, data: CategoryUpdateRequest) -> bool:
    # 查询 Category
    category = await Training_Categories.get_or_none(category_id=category_id)
    if not category:
        return False

    update_data = data.dict(exclude_unset=True)
    # 更新 Training_Categories 表
    if any(k in update_data for k in ['name', 'description']):
        await category.update_from_dict({
            k: v for k, v in update_data.items()
            if k in ['name', 'description']
        }).save()

    return True


async def delete_category(category_id: int) -> bool:
    category = await Training_Categories.get_or_none(category_id=category_id)
    if not category:
        return False

    # 先删除该分类下所有关联的 Training_Programs
    await Training_Programs.filter(category_id=category_id).delete()
    await category.delete()
    return True
